//
//  WKImageExtension.swift
//  商家端Swift
//
//  Created by 天下宅 on 16/9/12.
//  Copyright © 2016年 天下宅. All rights reserved.
//

import Foundation
import UIKit
extension UIImage
{
    static func creatImageWithColor(color:UIColor,size:CGSize) -> UIImage
    {
        var size = size
        if size.equalTo(CGSize.zero){
            size = CGSize(width:1, height:1)
        }
        let rect = CGRect(x:0, y:0, width:size.width, height:size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    //MARK: - 修改图片尺寸
    static func imageScaleToSize(image: UIImage, size: CGSize) -> UIImage{
        // 创建一个bitmap的context
        // 并把它设置成为当前正在使用的context
        // Determine whether the screen is retina
        if UIScreen.main.scale == 2.0{
            UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
        }else{
            UIGraphicsBeginImageContext(size)
        }
        
        // 绘制改变大小的图片
        image.draw(in: CGRect(x:0, y:0, width:size.width, height:size.height))
        
        // 从当前context中创建一个改变大小后的图片
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // 使当前的context出堆栈
        UIGraphicsEndImageContext()
        
        // 返回新的改变大小后的图片
        return scaledImage!
    }
    
    //MARK: - 压缩图片大小
    static func imageCompress(originalImage: UIImage) -> UIImage{
        guard let imageData = UIImageJPEGRepresentation(originalImage, 0.5) else{
            return originalImage
        }
        let compressImage = UIImage(data: imageData)!
        return compressImage
    }
}



var wkAssetID = "wk_assetID"
var wkIndex = "wk_index"

extension UIImage
{
    
    var wk_index:String?
    {
        set(newValue){
            objc_setAssociatedObject(self, &wkIndex, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        
        get
        {
            let index = (objc_getAssociatedObject(self, &wkIndex) ?? 0) as? String
            return index ?? ""
        }
    }
    var wk_assetID:String
    {
        set(newValue){
            objc_setAssociatedObject(self, &wkAssetID, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        
        get
        {
            let assetID = (objc_getAssociatedObject(self, &wkAssetID) ?? 0) as? String
            return assetID ?? ""
        }
    }
    
    func wk_isEqualImageTo(_ image:UIImage) -> Bool {
        return self.wk_assetID == image.wk_assetID
    }
}
